package com.javabasic.concurrency;


/**
 * 两个线程交替打印同一字符串
 * link:
 *  - https://www.cnblogs.com/friends-wf/p/3658258.html
 *  - https://blog.csdn.net/zhangliangzi/article/details/52733141
 */
public class MulitThreadTest {

    private static Object LOCK = new Object();
    private static String str = "Hello world";
    private static boolean flag = true;
    private static int curLen = 0;

    public static void main(String[] args) {
        final int len = str.length();
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                while (curLen < len) {
                    if (true == flag) {
                        synchronized (LOCK) {
                            flag = false;
                            System.out.println("线程A打印：" + str.charAt(curLen));
                            curLen++;
                            LOCK.notifyAll();
                            try {
                                LOCK.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                while (curLen < len) {
                    if (false == flag) {
                        synchronized (LOCK) {
                            flag = true;
                            System.out.println("线程B打印：" + str.charAt(curLen));
                            curLen++;
                            LOCK.notifyAll();
                            try {
                                LOCK.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                // 加上这句就会自动结束程序【要加在打印最后一个字母的线程】 这是因为要结束掉在wait的线程
                synchronized (LOCK) {
                    LOCK.notifyAll();
                }
            }
        };
        thread1.start();
        thread2.start();
    }


}
